<?php
require_once('Core/Model/Function/Abstract.php');

require_once('Core/Model/Table/Post.php');

class Core_Model_Function_Post extends Core_Model_Function_Abstract
{
    protected $_tablePost = null;

    public function __construct()
    {
        $this->_tablePost = new Core_Model_Table_Post;
    }

    public function findAllNotReadyForSearch() {
        $db = $this->_tablePost->getAdapter();
        $whereClause = $db->quoteInto('post_ready_for_search = ?', 0);
        $posts = $this->findAll($whereClause);
        return $posts;
    }

    public function updateReadyForSearch($id) {
        $data = array('post_ready_for_search' => 1);
        $this->save($data, $id);
        return $posts;
    }

    public function findAll($whereClause = false)
    {
        $result = array();

        if ($whereClause and !empty($whereClause)) {
            $posts = $this->_tablePost->fetchAll($whereClause);
        } else {
            $posts = $this->_tablePost->fetchAll();
        }

        if (null != $posts) {
            foreach ($posts as $post) {
                $author = $post->findDependentRowset('Core_Model_Table_User')->current();
                $result[] = array_merge($post->toArray(), $author->toArray());
            }
        }

        return $result;
    }

    public function findPostById($id)
    {
        $result = array();
        $post = $this->_tablePost->find($id)->current();
        if (null != $post) {
            $author = $post->findDependentRowset('Core_Model_Table_User')->current();
            $result = array_merge($post->toArray(), $author->toArray());
        }
        return $result;
    }

    public function save($data, $id = null)
    {
        if (null == $id) {
            $this->_tablePost->insert($data);
        } elseif (!empty($id)) {
            $db = $this->_tablePost->getAdapter();
            $where = $db->quoteInto('post_id = ?', $id);
            $this->_tablePost->update($data, $where);
        }
    }

    public function delete($id)
    {
        $db = $this->_tablePost->getAdapter();
        $where = $db->quoteInto('post_id = ?', $id);
        $this->_tablePost->delete($where);
    }

}